package org.trackcore.handler;

import org.trackcore.model.entity.PerformanceResource;
import org.trackcore.service.PerformanceResourceService;
import org.trackcore.utils.DataUtils;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
* 处理资源加载性能数据
* 处理器Key: "performance_resource"
*/
@Component
public class PerformanceResourceHandler implements DataHandler {

    private final PerformanceResourceService resourceService;

    public PerformanceResourceHandler(PerformanceResourceService resourceService) {
        this.resourceService = resourceService;
    }

    @Override
    public String getHandlerKey() {
        return "performance_resource"; // 对应type=performance, subType=resource
    }

    @Override
    public void handle(Map<String, Object> data, String logId) {
        PerformanceResource resource = PerformanceResource.builder()
                .logId(logId)
                .name(DataUtils.getString(data, "name"))          // 资源URL
                .sourceType(DataUtils.getString(data, "sourceType")) // script/link/img等
                .duration(DataUtils.getDouble(data, "duration"))
                .dns(DataUtils.getDouble(data, "dns"))       // 默认值0
                .tcp(DataUtils.getDouble(data, "tcp"))
                .ttfp(DataUtils.getDouble(data, "ttfp"))
                .protocol(DataUtils.getString(data, "protocol"))    // http/1.1等
                .responseHeaderSize(DataUtils.getInt(data, "responseHeaderSize"))
                .resourceSize(DataUtils.getInt(data, "resourceSize"))
                .startTime(DataUtils.getDouble(data, "startTime"))
                .build();

        resourceService.save(resource);
    }
}
